import { inject, Injectable } from '@angular/core';
import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest, HttpResponse } from '@angular/common/http';
import { finalize, Observable } from 'rxjs';
import { tap } from 'rxjs/operators';
import { LogService } from "../services/log-service.service";


@Injectable()
export class SunshineLoggerInterceptor implements HttpInterceptor {


  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    // let logService: LogService = inject(LogService);
    const startTime = Date.now(); // 记录请求开始时间
    let status: string; // 记录请求状态
    //请求拦截
    return next.handle(req).pipe(tap(event => status = event instanceof HttpResponse ? 'succeeded' : '',
      error => status = 'failed'), finalize(() => {
        const elapsedTime = Date.now() - startTime; // 请求最后结束时间
        const message = `${req.method} "${req.urlWithParams}" ${status} in ${elapsedTime} ms.`;
        // logService.log2(message);
        console.log(message)
      }))
  }
}
